<?php

namespace app\middleware;

use think\facade\Cache;

class UserAuth
{
	public function handle($request, \Closure $next)
	{
		$controller = $request->controller(true);
		if (in_array($controller, ['login', 'logout', 'captcha', 'browse'])) {
			return $next($request);
		}

		$header = $request->header();
		if(!is_array($header) ) {
			return json(['code'=> 401, 'msg'=> '您还没有登录,请登录后再试!']);
		}

		if(!isset($header['authorization'])){
			return json(['code'=> 401, 'msg'=> '您还没有登录,请登录后再试!']);
		}

		if(empty($header['authorization'])) {
			return json(['code'=> 401, 'msg'=> '您还没有登录,请登录后再试!']);
		}

		$header['authorization'] = substr($header['authorization'], 7);
		if(!Cache::has($header['authorization'])){
			return json(['code'=> 401, 'msg'=> '您还没有登录,请登录后再试!']);
		}

		$cache = Cache::get($header['authorization']);
		if(!is_array($cache) ) {
			return json(['code'=> 401, 'msg'=> '您还没有登录,请登录后再试!']);
		}

		if(!isset($cache['id'])){
			return json(['code'=> 401, 'msg'=> '您还没有登录,请登录后再试!']);
		}

		if(empty($cache['id'])){
			return json(['code'=> 401, 'msg'=> '您还没有登录,请登录后再试!']);
		}

		$cache['token'] = $header['authorization'];

		$request->sessInfo = $cache;

		return $next($request);
	}
}
